package org.daochong.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {
	private String encoding = "UTF-8";
	private boolean forceEncoding = true;

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		if ((this.encoding != null) && ((this.forceEncoding) || (request.getCharacterEncoding() == null))) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		if (config.getInitParameter("encoding") != null) {
			try {
				"".getBytes(config.getInitParameter("encoding"));
				this.encoding = config.getInitParameter("encoding");
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		if (config.getInitParameter("forceEncoding") != null)
			try {
				this.forceEncoding = Boolean.parseBoolean(config.getInitParameter("forceEncoding"));
			} catch (Throwable localThrowable1) {
			}
	}
}